//
//  QKOAuthViewController.m
//  QKWeibo-OC
//
//  Created by iMac_Kurt on 16/8/17.
//  Copyright © 2016年 Kurt_Qi. All rights reserved.
//

#import "QKOAuthViewController.h"
#import "NetworkTool.h"
#import "QKUserAccount.h"
#import "QKUserAccountViewModel.h"
#import <SVProgressHUD.h>

@interface QKOAuthViewController () <UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *webView;
@end

@implementation QKOAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadWebView];
    
    [self setupNav];
}

/// 加载webView
- (void)loadWebView {
    // webview加载请求
    [self.webView loadRequest:[NSURLRequest requestWithURL: [NetworkTool sharedTools].oauthURL]];
    
    // 代理
    self.webView.delegate = self;
    
    // 替换view
    self.view = self.webView;
}

/// 设置导航栏
- (void)setupNav {
    self.title = @"登录微博";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"退出" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"自动填充" style:UIBarButtonItemStylePlain target:self action:@selector(autoFill)];
}

#pragma mark - 监听方法
/// 自动填充用户名和密码
- (void)autoFill {
    
    NSString *jsString = @"document.getElementById('userId').value='18600970076';document.getElementById('passwd').value='iceqk32854';";
    
    [self.webView stringByEvaluatingJavaScriptFromString:jsString];
}
// 退出控制器
- (void)close {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UIWebViewDelegate
// webview加载请求时调用
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    // 目标：请求地址为百度的时候，不加载
    // 判断请求地址的主机地址是否为百度
    if (![request.URL.host isEqualToString:@"www.baidu.com"]) {
        return YES;
    }else {
        // 判断query是否以code=开头
        if (![request.URL.query hasPrefix:@"code="]) {
            [self close];
        }else {
            // 截取code
            NSString *code = [request.URL.query substringFromIndex:@"code=".length];
            //NSLog(@"%@", code);
            
            // 获取AccessToken
            [[QKUserAccountViewModel sharedUserAccount] loadAccessToken:code finished:^(BOOL isSuccessed) {
                if (isSuccessed == NO) {
                    NSLog(@"失败了");
                    
                    // 提示用户网络加载失败
                    [SVProgressHUD showInfoWithStatus:@"您的网络不给力，请稍后再试"];
                    [self dismissViewControllerAnimated:YES completion:^{
                        [SVProgressHUD dismiss];
                    }];
                    
                }else {
                    NSLog(@"成功了");
                    //NSLog(@"%@", [QKUserAccountViewModel sharedUserAccount].account);
                    
                    // 退出当前控制器
                    [self dismissViewControllerAnimated:YES completion:^{
                        // 切换控制器
                        [[NSNotificationCenter defaultCenter] postNotificationName:QKSwitchRootViewControllerNotification object:@"welcome"];
                    }];
                }
            }];
        }
        return NO;
    }
}

// 控制器webview加载loading
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [SVProgressHUD show];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [SVProgressHUD dismiss];
}

#pragma mark - 懒加载
- (UIWebView *)webView {
    if (_webView == nil) {
        UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        _webView = webView;
    }
    return _webView;
}

@end
